﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.GData.Client;
using Dropit.BlogPageProvider.Blog;

namespace Dropit.BlogPageProvider.Blogger
{
	public class Comment : IComment
	{
		public static List<Comment> List(Service service, BloggerId id)
		{
			return Utility.GetFeedEntries(service, GetFeedUrl(id)).Select<AtomEntry, Comment>(entry => new Comment()
							{
								BloggerId = new BloggerId()
								{
									BlogId = id.BlogId,
									PostId = id.PostId,
									CommentId = entry.Id.Uri.ToString()
								},
								Entry = entry,
								Heading = entry.Title.Text,
								Content = entry.Content.Content,
								Created = entry.Published
							})
							.ToList<Comment>();
		}

		public static Comment Load(Service service, BloggerId id)
		{
			return List(service, id).Find(entry => entry.BloggerId.CommentId == id.CommentId);
		}

		private static string GetFeedUrl(BloggerId id)
		{
			return string.Format("http://www.blogger.com/feeds/{0}/{1}/comments/default", Utility.ExtractBlogId(id.BlogId), Utility.ExtractPostId(id.PostId));
		}

		public static void Update(Service service, BloggerId id, IComment comment)
		{
			Comment oldComment = Comment.Load(service, id);
			if (oldComment != null)
			{
				AtomEntry entry = oldComment.Entry;
				entry.Title.Text = comment.Heading;
				if (entry.Content == null)
				{
					entry.Content = new AtomContent();
				}
				entry.Content.Content = comment.Content;
				entry.Update();
			}
		}

		public static Comment SaveNew(Service service, BloggerId parentId, IComment comment)
		{
			AtomEntry newComment = new AtomEntry();
			newComment.Title.Text = comment.Heading;
			newComment.Content = new AtomContent();
			newComment.Content.Content = comment.Content;
			newComment.Content.Type = "xhtml";

			Uri blogFeedUri = new Uri(GetFeedUrl(parentId));
			AtomEntry newEntry = service.Insert(blogFeedUri, newComment);
			return new Comment()
			{
				BloggerId = new BloggerId()
				{
					BlogId = parentId.BlogId,
					PostId = parentId.PostId,
					CommentId = newEntry.Id.Uri.ToString()
				},
				Entry = newEntry,
				Heading = newEntry.Title.Text,
				Content = newEntry.Content.Content,
				Created = newEntry.Published
			};
		}

		public static void Delete(Service service, BloggerId id)
		{
			Comment comment = Comment.Load(service, id);
			if (comment != null && comment.Entry != null)
			{
				comment.Entry.Delete();
			}
		}

		public string Id
		{
			get { return BloggerId.ToString(); }
		}

		public BloggerId BloggerId { get; set; }
		public AtomEntry Entry { get; set; }
		public string Heading { get; set; }
		public string Content { get; set; }
		public DateTime Created { get; set; }
	}
}